<template>
<div v-loading.fullscreen.lock="fullscreenLoading">

  <el-container>
    <el-header>
        <el-row>
          <el-col :span="24">
            <Title></Title>
          </el-col>
        </el-row>

    </el-header>
    <el-main>
<!--      输入框-->
              <el-row>
                <el-col :span="24">
                  <div>


                    <el-row  :gutter="10">
                      <el-col :span="4">
                        <el-upload
                            ref="upload"
                            action="https://jsonplaceholder.typicode.com/posts/"
                            class="upload-demo"
                            accept="xls,xlsx"
                            :show-file-list="false"
                            :auto-upload="false"
                            :multiple="false"
                            :on-change="fileOnChange">
                          <el-button slot="trigger" size="small" type="primary"  icon="el-icon-plus">处方导入</el-button>

                        </el-upload>
                      </el-col>
                      <el-col :span="2"  style="margin-top: 7px "><div class="medicineLabel" >置信度：</div></el-col>

                      <el-col :span="3">

                        <el-input v-model="ConfidenceInput" placeholder="请输入置信度"></el-input>
                      </el-col>
                      <el-col :span="4" style="margin-top: 10px;margin-right:-40px;padding-left: 30px;">
                        <div class="sortLabel">
                          <span>阈值：</span>
                        </div>
                      </el-col>
                      <el-col :span="4">
                        <div class="grid-content bg-purple-light">
                          <el-input v-model="SupportInput" placeholder="请输入支持度"></el-input>
                        </div>
                      </el-col>

                      <el-col :span="6" style=";padding-left: 40px" ><el-button type="primary" @click="sendJsonData_to_backend_Association"  >确定</el-button>
<!--                        <el-button type="primary" style="margin-left: 20px" @click="downloadAssociation">下载</el-button>-->
                        <el-button
                            style="margin-left: 60px"
                            type="primary"
                        >
                          <download-excel class="export-excel-wrapper" :data="tableData" :fields="json_fieldsAssociation" name="">
                          </download-excel>
                        </el-button>
                      </el-col>
                    </el-row>
                    <div class="fengexian"></div>
                  </div>
                </el-col>
              </el-row>
      <div class="block">
        <el-row :gutter="20">
<!--          table-->
          <el-col :span="8">
            <div class="grid-content">
              <el-table

                  :show-header="flagTable"
                  :data="currentPageList"
                  border
                  style="width: 90%">
                <el-table-column
                    prop="id"
                    label="编号"
                    width="156">
                </el-table-column>
                <el-table-column
                    width="268"
                    prop="medicines"
                    label="药物">
                </el-table-column>
              </el-table>

              <el-pagination v-if="flagTable"
                  style="justify-content: center;align-items:center;display: flex "
                  small
                  page-size="7"
                  @current-change="currentOnchange"
                  @prev-click="prevOnclick"
                  @next-click="nextOnclick"
                  @size-change="sizeOnchange"
                  layout="prev, pager, next"
                  :total="totalSize">
              </el-pagination>
          </div>
          </el-col>
<!--          网络图-->
<!--          background: #20b8f1"-->
          <el-col :span="8">
            <div style="height: 600px ; ">
            <div  id="echartsGraph" style="width: 480px;height: 370px ; padding-bottom: 100px"></div>
          </div>
          </el-col>
<!--          background: rgba(70,199,40,0.32);-->
          <el-col :span="8"><div style="height: 400px">

         <div id="contentCenterDIV">
           <div id="medicineImgUrl">
             <el-image v-if="flagSQL"
                       style="width: 150px; height: 150px"
                       :src=this.MySQLData.imgurl
             ></el-image>
           </div>
            <div id="medicineNameDIV">
              <div id="medicineNANE" v-if="flagSQL">药名：</div>
              <div id="medicineVALUE" > {{this.MySQLData.medicinename}}</div>
            </div>
           <div id="efficacyDIV">
             <div id="efficacyNAME" v-if="flagSQL">功效：</div>
             <div id="efficacyVALUE">{{this.MySQLData.efficacy}}</div>
           </div>
           <div id="propertiesDIV">
             <div id="propertiesNAME" v-if="flagSQL" >性状:</div>
             <div id="propertiesVALUE">{{this.MySQLData.properties}}</div>
           </div>
         </div>

          </div>
          </el-col>
        </el-row>

      </div>
    </el-main>
    <el-footer><FooterTitle></FooterTitle></el-footer>
  </el-container>


</div>
</template>

<script>

var XLSX = require("xlsx");
import Title from "../../components/Title";
import FooterTitle from "../../components/FooterTitle";
export default {
  name: "AssociationAnalysis",
  components:{
    Title,
    FooterTitle
  },
  data(){
    return{
      //网络图中的data
      netData:Array,
      data:Array,
      LinkeData:Array,
      //保存分页底部的大小
      totalSize:42,
      //保存page的页数,默认为1
      pageVal:1,
      currentPageList:Array,
      //保存7条记录（将后端传回来的值进行切割）
      pageList:Array,
      //保存支持度，阈值，json数据
      SupportInput:"",
      ConfidenceInput:"",
      association_excel_json:"",
      //
      EchartAssociationColum:'',
      tableData: Array,
      //数据库所需要的

      //
//设置网络图的参数
      optionAssocation :{
        title: {
          text: '网络图'
        },
        legend:{
        align:"left",
          marginLeft:-15,
        },
        tooltip: {},
        animationDurationUpdate: 1500,
        animationEasingUpdate: 'quinticInOut',
        toolbox: {

          feature: {
            mark:{show:true},
            saveAsImage: {
              show: true,
              pixelRatio:1,
              title:"下载",
              type:'png',
              lang:['点击保存'],
              name:"关联分析网络图"
            }
          }
        },
        series: [
          {



            right:20,
            // bottom:20,
            type: 'graph',
            layout:"force",
            roam: true,
            draggable: true,
            force: {
              initLayout:"circular" ,//力引导的初始化布局，默认使用xy轴的标点
              repulsion: 10000, //节点之间的斥力因子。支持数组表达斥力范围，值越大斥力越大。
              gravity: 2, //节点受到的向中心的引力因子。该值越大节点越往中心点靠拢。
              edgeLength: 50, //边的两个节点之间的距离，这个距离也会受 repulsion。[10, 50] 。值越小则长度越长
              layoutAnimation: true
              //因为力引导布局会在多次迭代后才会稳定，这个参数决定是否显示布局的迭代动画，在浏览器端节点数据较多（>100）的时候不建议关闭，布局过程会造成浏览器假死。
            },
            // symbolSize:30,
            label: {
              show: true,
              text: 'hhh'
            },
            symbolSize: (rawValue, params) => {
              console.log(params)
              console.log(params.data)
              console.log(params.dataIndex)
              return 30
            },

            focusNodeAdjacency: true,
            edgeSymbol: ['circle', 'arrow'],
            // edgeSymbolSize: [10, 200],
            // edgeLabel: {
            //   fontSize: 12
            // },

            itemStyle: {
              //配置节点的颜色已及尺寸
              normal: {
                // （1） 直接写一个颜色，这样的结果是所有节点都是同一个颜色
                  // color: '#DC143C',
                borderWidth:"auto"
              },

            },

            links:Array,

            data:Array,
            // links: [],
            lineStyle: {
              opacity: 0.9,
              width: 2,
              curveness: 0
            }
          }
        ]
      },
      //保存查询到数据库的值
      MySQLData:"",
      //使得 性状，功效，名称展示的一个变量
      flagSQL:false,
      //表格展示
      flagTable:false,
      //加载
      fullscreenLoading: false,
      //下载需要的数据格式
      json_fieldsAssociation:{
        "编号": "id", //常规字段
        "药物":"medicines",
      },
      AssociationTableAll:Array
    }
  },
  mounted() {
  },
  methods:{
    openFullScreen() {
      this.fullscreenLoading = true;
      setTimeout(() => {
        this.fullscreenLoading = false;
      }, 2000);
    },
    fileOnChange(file, fileList){
      let files = {0:file.raw}
      this.readExcel1(files);
    },
    readExcel1(files) {//表格导入
      var that = this;
      if(files.length<=0){//如果没有文件名
        return false;
      }else if(!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())){

        this.$message.error('上传格式不正确，请上传xls或者xlsx格式');
        return false;
      }
      const fileReader = new FileReader();
      fileReader.onload = (ev) => {
        try {
          const data = ev.target.result;
          const workbook = XLSX.read(data, {
            type: 'binary'
          });

          const wsname1 = workbook.SheetNames[0];//取第一张表
          console.log(wsname1)
          const ws1 = XLSX.utils.sheet_to_json(workbook.Sheets[wsname1]);//生成第一张表的json表格内容
          console.log(ws1.length)
          var medicineArray = new Array();
          for(var i=0;i<ws1.length;i++){
            medicineArray.push(ws1[i].处方)
          }

          //console.log(medicineArray)

          this.association_excel_json = medicineArray;
          console.log(this.association_excel_json);
          console.log(typeof (this.association_excel_json))
          //当我点击确定按钮的时候提交数据
          // this.sendJsonData_to_backend()
          try{
          }catch(err){
            console.log(err)
          }
          this.$refs.upload.value = '';
        } catch (e) {
          return false;
        }
      };
      fileReader.readAsBinaryString(files[0]);
    },
    //对两个输入框的数据进行校验
    check_data(association_excel_json,SupportInput,ConfidenceInput){
      console.log("ConfidenceInput"+ConfidenceInput)
      console.log("SupportInput--"+SupportInput)
     if(association_excel_json.length==0) {
       this.$message({
         message: '请传入excel处方',
         center: true,
         type: 'error'
       });
     }else  if((ConfidenceInput>=0&&ConfidenceInput<=1)&&(SupportInput>=1)){
       //加载方法
       this.openFullScreen()
       //返回表格数据
      this.returnTableData();
      //返回网络数据
      this.returnNetData();
     }else{
       this.$message({
         message: '请输入0~1范围内的支持度和阈值 ',
         center: true,
         type: 'error'
       });
     }
    },
    //  //返回table 数据  形如---“{熟地, 白芍}->{当归}”
    returnTableData(){
      let that = this
      this.$axios.post('http://localhost:8800/association', {
        //传递支持度，阈值，json，页码
        ConfidenceInput:that.ConfidenceInput,
        SupportInput:that.SupportInput,
        json:that.association_excel_json,
        pageVal:that.pageVal,
      })
          .then(function(response) {
            that.flagTable = true;
            that.tableData = JSON.parse(JSON.stringify(response.data))
            that.totalSize = that.tableData.length
            console.log("that.tableData.length:"+that.tableData.length)
            //返回前七条数据
            let AllListSize = that.tableData.length
            // console.log("AllListSize:"+AllListSize
            if(AllListSize>7){
              that.currentPageList=JSON.parse(JSON.stringify(that.tableData.slice(0,7)));
            }else{
              that.currentPageList=JSON.parse(JSON.stringify(that.tableData.slice(0,AllListSize)));
            }





            //初始化网络图
            //  that.initNetChartDiagram()
          }).catch(function(error) {
        console.log("error")
      })
    },
    //返回网络图数据
    returnNetData(){
      let that = this
      this.$axios.post('http://localhost:8800/netdata', {
        //传递支持度，阈值，json，页码
        ConfidenceInput:that.ConfidenceInput,
        SupportInput:that.SupportInput,
        json:that.association_excel_json,
        pageVal:that.pageVal,
      })
          .then(function(response) {
            console.log("data--------------------")
            //console.log(response.data.data)
            that.netData=JSON.parse(JSON.stringify(response.data.data))
           that.data = JSON.parse(JSON.stringify(response.data.name))
            // console.log(JSON.parse(JSON.stringify(response.data.data)))
            // console.log(JSON.stringify(response.data.name))
            that.initNetChartDiagram();

          }).catch(function(error) {
        console.log("error")
      })
    },

    //初始化网络图
    initNetChartDiagram(){
      console.log("initNetChartDiagram")
      this.optionAssocation.series[0].links =JSON.parse(JSON.stringify(this.netData))
      this.optionAssocation.series[0].data =JSON.parse(JSON.stringify(this.data))
      this.EchartAssociationColum = this.$echarts.init(document.getElementById("echartsGraph"));
      this.EchartAssociationColum.setOption(this.optionAssocation)
      var that=this;
      //查询mysql的方法，点击单个节点触发
      //调用数据库，查询药物的功效等信息
      this.EchartAssociationColum.on('click',function (params) {
        that.$axios.post('http://localhost:8800/searchMedicine', {
          MName:params.name
        })
            .then(function(response) {
              console.log(response.data)
              that.MySQLData= JSON.parse(JSON.stringify(response.data));
              that.flagSQL = true;
              // that.medicinename =response.data.medicinename;
              // that.efficacy =response.data.efficacy;
              // that.properties =response.data.properties;

            }).catch(function(error) {
          console.log("error")
        })

      })

    },



    //点击按钮将数据传送给后端
    sendJsonData_to_backend_Association(){
      //校验数据
      console.log(typeof (parseFloat(this.SupportInput)));
      console.log(typeof (parseFloat(this.ConfidenceInput)))
      this.check_data(this.association_excel_json,parseInt(this.SupportInput),parseFloat(this.ConfidenceInput));

    },
    //当页数发生改变时，触发的事件
    sizeOnchange(val){
      console.log(`pageSize 改变时会触发 ${val} 条`);
      this.pageVal = val
      //返回前七条数据
      let AllListSize = this.tableData.length
      if((AllListSize-7*(this.pageVal-1))>0){
        console.log("(AllListSize-7*(this.pageVal))>7:::"+(AllListSize-7*(this.pageVal))>7)
        this.currentPageList=JSON.parse(JSON.stringify(this.tableData.slice(7*(this.pageVal-1),7*this.pageVal)));
      }else{
        this.currentPageList=JSON.parse(JSON.stringify(this.tableData.slice((AllListSize-7*(this.pageVal-2)),(AllListSize-7*(this.pageVal-1)))));
      }
      console.log(`前一页 ${val} 条`);

},
    currentOnchange(val){
      this.pageVal = val
      //返回前七条数据
      let AllListSize = this.tableData.length
      if((AllListSize-7*(this.pageVal-1))>0){
        console.log("(AllListSize-7*(this.pageVal))>7:::"+(AllListSize-7*(this.pageVal))>7)
        this.currentPageList=JSON.parse(JSON.stringify(this.tableData.slice(7*(this.pageVal-1),7*this.pageVal)));
      }else{
        this.currentPageList=JSON.parse(JSON.stringify(this.tableData.slice((AllListSize-7*(this.pageVal-2)),(AllListSize-7*(this.pageVal-1)))));
      }
      console.log(`当前页: ${val} `);
    },
    prevOnclick(val){
      this.pageVal = val
      //返回前七条数据
      let AllListSize = this.tableData.length
      if((AllListSize-7*(this.pageVal-1))>0){
        console.log("(AllListSize-7*(this.pageVal))>7:::"+(AllListSize-7*(this.pageVal))>7)
        this.currentPageList=JSON.parse(JSON.stringify(this.tableData.slice(7*(this.pageVal-1),7*this.pageVal)));
      }else{
        this.currentPageList=JSON.parse(JSON.stringify(this.tableData.slice((AllListSize-7*(this.pageVal-2)),(AllListSize-7*(this.pageVal-1)))));
      }
      console.log(`前一页 ${val} 条`);
    },
    nextOnclick(val){
      this.pageVal = val

      //返回前七条数据
      let AllListSize = this.tableData.length
      if((AllListSize-7*(this.pageVal-1))>0){
        console.log("(AllListSize-7*(this.pageVal))>7:::"+(AllListSize-7*(this.pageVal))>7)
        this.currentPageList=JSON.parse(JSON.stringify(this.tableData.slice(7*(this.pageVal-1),7*this.pageVal)));
      }else{
        this.currentPageList=JSON.parse(JSON.stringify(this.tableData.slice((AllListSize-7*(this.pageVal-2)),(AllListSize-7*(this.pageVal-1)))));
      }
      console.log(`下一页 ${val} 条`);
    },
  }
}
</script>

<style scoped>
.test{
  background: #20b8f1;
  display: flex;
  text-align: center;
  padding-left: 500px;
}
/*.grid-content{*/
/*  background: #da0758;*/
/*  height: 400px;*/


/*}*/
.fengexian{
  position: relative;
  /*margin: 15px ;*/
  margin-top: 25px;
  margin-bottom: 25px;
  width:100%;
  height: 1px;
  background-color: #d4d4d4;
  text-align: center;
  font-size: 16px;
  color: rgba(101, 101, 101, 1);

}
#medicineImgUrl{
  margin-bottom: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}
#contentCenterDIV{
  width: 100%;
  height: 100%;
  /*background: #da0758;*/
}
#medicineNameDIV{
  width: 100%;
  height: 10%;
  /*background: #20b8f1;*/
  display: flex;
}

#medicineNANE{
  font-size: medium;
  font-family: 方正粗黑宋简体;;
  width: 150px;
}
#medicineVALUE{
  font-size: medium;
  font-family: 宋体;
}
#efficacyDIV{
  width: 100%;
  height: 40%;
  /*background: #9b5572;*/
  display: flex;
}
#efficacyNAME{
  font-size: medium;
  font-family: 方正粗黑宋简体;;
  width: 100px;
  /*background: #da0758*/
}
#efficacyVALUE{
  font-size: medium;
  font-family: 宋体;
}
#propertiesDIV{
  width: 100%;
  height: 50%;
  /*background: #7b77f1;*/
  display: flex;
}
#propertiesNAME{
  font-size: medium;
  font-family: 方正粗黑宋简体;;
  width: 250px;
  /*background: #da0758*/
}

#propertiesVALUE{
  font-size: medium;
  font-family: 宋体;
}
.divColor{
  background: yellow;
}
</style>
